package org.wcms.surrounded.persistence;

import java.util.List;
import java.util.Map;

import org.wcms.surrounded.Constants;
import org.wcms.surrounded.model.User;

import com.google.inject.Inject;
import com.google.inject.name.Named;
import com.googlecode.objectify.Objectify;

public class UserService {

    private final Objectify service;
    private final User newUser;
    
    @Inject
    public UserService(Objectify service, 
            @Named(Constants.SURROUNDED_NEW_USER_NAME) User newUser) {
        this.service = service;
        this.newUser = newUser;
    }
    
    public void addUser(User user) {
        if (user != null && user.getId() != null && 
                user.getId() == Constants.SURROUNDED_NEW_USER_ID) {
            return;
        }
        service.put(user);
    }
    
    public void updateUser(User user) {
        if (user.getId() == null) {
            return;
        }
        addUser(user);
    }
    
    public User getUserById(long id) {
        if (id == Constants.SURROUNDED_NEW_USER_ID) {
            return newUser;
        }
        return service.query(User.class).filter("id", id).get();
    }
    
    public User getUserByToken(String accessToken) {    	
        return service.query(User.class).filter("accessToken", accessToken).get();        
    }
    
    public User getUserByfbId(String fbId) {    	
        return service.query(User.class).filter("fbId", fbId).get();        
    }

    public Map<Long, User> getUsersByIds(List<Long> ids) {
        return service.get(User.class, ids);
    }
    
    public void deleteUser(User userToBeDeleted) {
    	service.delete(userToBeDeleted);
    }
    
    public Iterable<User> getUsersWithLowerScore(User cause) {
        return service.query(User.class)
                      .filter("score <", cause.getScore());
    }
    
}
